//
//  ProfitCaculator.js
//  SugLisSystem
//
//  Created by Mr.Right on 2013-04-07.
//  Copyright 2013 Mr.Right. All rights reserved.
//  最难抉择的事情是在两个梦想中间❤~

var dB = require('untils/DB');
var pubFun = require('untils/PubFun');
var exeSQL = require('untils/ExeSQL');
var polSubDataHandler = require('corecenter/PolSubDataHandler');
var tGlobalInput = require('GlobalInput');

var headintroducePath = 'suggestJSON/headintroduce.json';
var caldatariskresourcePath = 'suggestJSON/caldatariskresource.json';
var picElementPath = 'suggestJSON/picElement.json';
var headerEleNamePath = 'suggestJSON/headerEleName.json'

function ProfitCaculator(mainPolNo) {
	this.mainPolNo = mainPolNo;

	var LSPolDB = new dB('LSPol');
	LSPolDB['polno'] = mainPolNo;
	if (LSPolDB.getInfo()) {
		this.mainRiskCode = LSPolDB['riskcode'];
	}

	this.subRisks = [];
	var subRiskSQL = "SELECT RISKCODE FROM LSPOL WHERE POLNO <> MAINPOLNO AND MAINPOLNO = '" + mainPolNo + "'";
	LSPolDB.clear();
	var LSPolSet = LSPolDB.executeQuery(subRiskSQL);
	for (var i = 0; i < LSPolSet.length; i++) {
		this.subRisks.push(LSPolSet[i]['riskcode']);
	}

}

/**
 * 计算单个险种的收益数据
 * */
function calculate(lsPolSchema) {
	//险种代码
	var riskCode = lsPolSchema['riskcode'];
	//渠道
	var chanlesign = tGlobalInput.chanlesign;
	//最终表头
	var caldatariskresourceJSON = Ti.Filesystem.getFile(caldatariskresourcePath).read().toString();
	var caldatariskresourceObject = JSON.parse(caldatariskresourceJSON);
	var riskTAFlag = caldatariskresourceObject[riskCode + 'TA'].toString();
	//var headFlag = riskTAFlag.split(',');
	//Ti.API.warn('[ProfitCaculator]险种' + riskCode + '表头:' + headFlag.toString());
	//TODO---------------- 特殊处理 --------------------------

	if (riskCode == '00116500' && transProfitExpress('$PolM.riskcode', lsPolSchema) == '00111000') {
		if (chanlesign == '1') {
			riskTAFlag = caldatariskresourceObject['00116501TA'].toString();
			var headFlag = riskTAFlag.split(',');
			Ti.API.warn('[ProfitCaculator]险种' + riskCode + '表头:' + headFlag.toString());
			var omniProfitCaculator = require('corecenter/OmniProfitCaculator_00116501');
			var omniPC = new omniProfitCaculator(lsPolSchema, transProfitExpress('$PolM', lsPolSchema), headFlag);
			var tempCData = omniPC.reOrderData();
			return {
				hData : headFlag,
				cData : tempCData
			}
		}
	}

	if (chanlesign == '5' && riskCode == '00116500') {
		riskTAFlag = caldatariskresourceObject['00116550TA'].toString();
	}

	var headFlag = riskTAFlag.split(',');
	Ti.API.warn('[ProfitCaculator]险种' + riskCode + '表头:' + headFlag.toString());

	if (riskCode == '00111000') {
		var tempLsPolDB = new dB('LSPol');
		tempLsPolDB['mainpolno'] = lsPolSchema['polno'];
		tempLsPolDB['riskcode'] = '00116500';
		if (tempLsPolDB.query().length > 0) {
			tempHeadFlag = [];
			var SKIP_HEAD = ['LJSXS', 'LJSX_D', 'LJSX_Z', 'LJSX_G'];
			for (var i = 0; i < headFlag.length; i++) {
				var tempFlag = headFlag[i];
				if (SKIP_HEAD.indexOf(tempFlag) == -1) {
					tempHeadFlag.push(tempFlag);
				}
			}
			headFlag = tempHeadFlag;
		}
	}

	//最终收益数据
	var calculateData = new Object();
	//万能险的特殊处理
	if (riskCode == '00116500') {
		var omniProfitCaculator = require('corecenter/OmniProfitCaculator_00116500');
		var omniPC = new omniProfitCaculator(lsPolSchema, transProfitExpress('$PolM', lsPolSchema), headFlag);
		var tempCData = omniPC.reOrderData();
		return {
			hData : headFlag,
			cData : tempCData
		}
	}
	//---------------- 特殊处理结束 --------------------------
	//初始化收益相关
	var tableP_sql = "Select * From ProceedsExpress Where RiskCode='" + riskCode + "' order by CalOrderNo";
	var ProceedsExpressDB = new dB('ProceedsExpress');
	var ProceedsExpressSet = ProceedsExpressDB.executeQuery(tableP_sql);
	for (var m = 0; m < ProceedsExpressSet.length; m++) {
		var ProceedsExpressSchema = ProceedsExpressSet[m];
		//获取收益项
		var proceedsCode = ProceedsExpressSchema['proceedscode'];
		//相关收益因子计算表达式
		var calexPress = ProceedsExpressSchema['calexpress'];
		//算法类型
		var expressProperty = ProceedsExpressSchema['expressproperty'];

		//3类算法
		if (expressProperty == '3') {
			calculateData[proceedsCode] = calProceedExpress(calexPress, calculateData);
			Ti.API.warn('[ProfitCaculator]' + proceedsCode + '：' + calculateData[proceedsCode].toString());
			continue;
		}
		//TODO 6类算法
		if (expressProperty == '6') {
			//初始值
			calculateData[proceedsCode] = [];
			calculateData[proceedsCode][0] = parseFloat(ProceedsExpressSchema['recursioninitvalue']);
			var exp_first = translateFirstStep(calexPress)
			var size = transProfitExpress(ProceedsExpressSchema['remark'], lsPolSchema);
			calSixProceedExpress(calculateData, proceedsCode, exp_first, size);
			Ti.API.warn('[ProfitCaculator]' + proceedsCode + '：' + calculateData[proceedsCode].toString());
			continue;
		}
		// TODO 7类算法
		if (expressProperty == '7') {
			var sql = transProfitExpress(calexPress, lsPolSchema);
			var rs = exeSQL.execSQL(sql, exeSQL.TYPE_ARRAY);
			calculateData[proceedsCode] = [];
			var size = transProfitExpress(ProceedsExpressSchema['remark'], lsPolSchema);
			for (var n = 0; n < size; n++) {
				calculateData[proceedsCode][n] = rs[n][0];
			}
			Ti.API.warn('[ProfitCaculator]' + proceedsCode + '：' + calculateData[proceedsCode].toString());
			continue;
		}
		// TODO 8类算法
		if (expressProperty == '8') {
			calculateData[proceedsCode] = transProfitExpress(calexPress, lsPolSchema);
			Ti.API.warn('[ProfitCaculator]' + proceedsCode + '：' + calculateData[proceedsCode].toString());
			continue;
		}

		var calexObject = {};
		//获取C表数据
		var tableC_sql = "Select * From CALCUTEELEMET Where RiskCode='" + riskCode + "' and itemcode = '" + proceedsCode + "' order by CalOrderNo";
		var tempCalcuteElemetDB = new dB('CalcuteElemet');
		var tempCalcuteElemetSet = tempCalcuteElemetDB.executeQuery(tableC_sql);
		for (var n = 0; n < tempCalcuteElemetSet.length; n++) {
			var tempCalcuteElemetSchema = tempCalcuteElemetSet[n];
			//收益因子
			var calelement = tempCalcuteElemetSchema['calelement'];
			if (calexObject[calelement] == null) {
				calexObject[calelement] = [];
			}
			//计算类型
			var sqlExcuteType = tempCalcuteElemetSchema['sqlexcutetype'];
			//计算表达式
			var calSql = tempCalcuteElemetSchema['calsql'];
			//保留位数
			var resultPreciSion = tempCalcuteElemetSchema['resultprecision'];
			if (resultPreciSion == null) {
				resultPreciSion = 0;
			}
			//处理开始和结束点
			var startPoint = tempCalcuteElemetSchema['startpoint'];
			if (startPoint == null) {
				startPoint = '1';
			}
			//表达式计算
			startPoint = eval(transExpress(startPoint, lsPolSchema));
			var startPointFlag = tempCalcuteElemetSchema['startpointflag'];
			//处理开始标记
			if (startPointFlag == 'A') {
				startPoint = startPoint - lsPolSchema['insuredappage'];
			}
			var endPoint = tempCalcuteElemetSchema['endpoint'];

			//表达式计算
			endPoint = eval(transExpress(endPoint, lsPolSchema));
			var endPointFlag = tempCalcuteElemetSchema['endpointflag'];
			//处理开始标记
			if (endPointFlag == 'A') {
				endPoint = endPoint - lsPolSchema['insuredappage'];
			}

			if (sqlExcuteType == '0') {
				//计算类型0
				var tempSql = transExpress(calSql, lsPolSchema);
				var data = exeSQL.execSQL(tempSql, exeSQL.TYPE_ARRAY);
				for (var i = startPoint - 1; i < endPoint && i < data.length; i++) {
					//TODO 保留小数位数
					// calexObject[calelement][i] = Math.round(data[i][0] * 100) / 100;
					calexObject[calelement][i] = pubFun.round(data[i][0], resultPreciSion);
				}
			} else if (sqlExcuteType == '1') {
				//计算类型1
				var tempSql = transExpress(calSql, lsPolSchema);
				var data = exeSQL.getOneValue(tempSql);
				for (var i = startPoint - 1; i < endPoint; i++) {
					//TODO 保留小数位数
					// calexObject[calelement][i] = Math.round(data * 100) / 100;
					calexObject[calelement][i] = pubFun.round(data, resultPreciSion);
				}
			} else if (sqlExcuteType == '2') {
				//初始值
				var initValue = tempCalcuteElemetSchema['initvalue'];
				if (initValue == null) {
					initValue == '1';
				}
				initValue = eval(transExpress(initValue, lsPolSchema));
				initValue = parseFloat(initValue);
				//初始值
				var stepValue = tempCalcuteElemetSchema['stepvalue'];
				if (stepValue == null) {
					stepValue == '1';
				}
				stepValue = eval(transExpress(stepValue, lsPolSchema));
				stepValue = parseFloat(stepValue);

				for (var i = startPoint - 1; i < endPoint; i++) {
					//TODO 保留小数位数
					// calexObject[calelement][i] = initValue;
					calexObject[calelement][i] = pubFun.round(initValue, resultPreciSion);
					initValue += stepValue;
				}
			}

		}

		calculateData[proceedsCode] = calProceedExpress(calexPress, calexObject);
		Ti.API.warn('[ProfitCaculator]' + proceedsCode + '：' + calculateData[proceedsCode].toString());
	}

	var profitData = {
		hData : headFlag,
		cData : calculateData
	}

	return profitData;
}

/**
 * 预留方法，合并收益用
 * @param data1
 * @param data2
 * */
function MergeCaculateData(data1, data2) {
	//判断较大的数组
	var length_1 = 0;
	for (var obj in data1.cData) {
		length_1 = data1.cData[obj].length;
		break;
	}
	var length_2 = 0;
	for (var obj in data2.cData) {
		length_2 = data2.cData[obj].length;
		break;
	}
	var length_max = Math.max(length_1, length_2);

	var oriData;
	var addData;

	if (length_max == length_1) {
		oriData = data1;
		addData = data2;
	} else {
		oriData = data2;
		addData = data1;
	}
	//特殊标记设定
	var SKIP_FLAG_ARR = ['BDND', 'BDND_W'];
	var ZERO_FLAG_ARR = ['JBBF', 'SGBXJ'];

	var ori_hData = oriData.hData;
	var add_hData = addData.hData;
	var ori_cData = oriData.cData;
	var add_cData = addData.cData;
	//扩展增加数据
	for (var m = 0; m < add_hData.length; m++) {
		var tempHead = add_hData[m];
		if (ZERO_FLAG_ARR.indexOf(tempHead) == -1) {
			for (var n = add_cData[tempHead].length; n < length_max; n++) {
				add_cData[tempHead].push(add_cData[tempHead][n - 1]);
			}
		} else {
			for (var n = add_cData[tempHead].length; n < length_max; n++) {
				add_cData[tempHead].push(0);
			}
		}
	}

	//数据相加
	for (var m = 0; m < add_hData.length; m++) {
		var tempHead = add_hData[m];
		if (SKIP_FLAG_ARR.indexOf(tempHead) != -1) {
			Ti.API.warn('[ProfitCaculator]跳过表头:' + tempHead);
			continue;
		}
		if (ori_hData.indexOf(tempHead) == -1) {
			Ti.API.warn('[ProfitCaculator]增加表头:' + tempHead);
			ori_hData.push(tempHead);
			ori_cData[tempHead] = add_cData[tempHead];
		} else {
			Ti.API.warn('[ProfitCaculator]相加表头:' + tempHead);
			for (var n = 0; n < length_max; n++) {
				ori_cData[tempHead][n] += add_cData[tempHead][n];

			}
		}
	}

	return oriData;
}

function calProceedExpress(express, calexObject) {
	//表达式结果
	var result = [];
	//获取最大数组长度
	var maxLength = 0;
	for (var obj in calexObject) {
		maxLength = Math.max(maxLength, calexObject[obj].length);
	}

	for (var i = 0; i < maxLength; i++) {
		// 定义变量字符串
		var definedString = '';
		for (var obj in calexObject) {
			var objValue = calexObject[obj][i];
			if (objValue == null) {
				objValue = 0;
			}
			definedString += ('var ' + obj + ' = ' + objValue + ';');
		}
		//定义$Self$
		if (i == 0) {
			definedString += ('var $Self$ = 0;');
		} else {
			definedString += ('var $Self$ = ' + result[i - 1] + ';');
		}

		eval(definedString);
		result.push(eval(express));
	}
	return result;
}

/**
 * 计算6类收益
 * */
function calSixProceedExpress(calculateData, calCode, express, size) {
	var evalstring = '';
	for (var obj in calculateData) {
		evalstring += ('var ' + obj + ' = calculateData.' + obj + ';' );
	}
	evalstring += "for (var n = 1; n < size; n++) {";
	evalstring += "var i = n - 1;";
	evalstring += "for(var __n=0;__n<1;__n++){";
	evalstring += translateSecorndStep(express, calCode);
	evalstring += "}";
	evalstring += "}";
	eval(evalstring);
}

/**
 * 替换变量
 * @param express 表达式
 * */
function translateFirstStep(express) {
	var start = 0;
	var end = 0;
	while (true) {
		start = express.indexOf("≮");
		end = express.indexOf("≯");
		if (start == -1 || end == -1) {
			break;
		}
		var temp = express.substring(start, end + 1);
		var exp = temp.substring(1, temp.length - 1);
		if (exp.indexOf('(') != -1) {
			var indexPo = exp.indexOf('(');
			var tempstr = exp.substring(0, indexPo);
			exp = exp.replace(/\(/g, '[n');
			exp = exp.replace(/\)/g, ']');
		} else {
			exp = exp + "[n]";
		}
		eval("express = escape(express).replace(/" + escape(temp) + "/g, '" + exp + "')");
		express = unescape(express);
	}
	return express;
}

function translateSecorndStep(exp, ItemCode) {
	if (exp != null && exp.indexOf("return") == -1) {
		return "{ " + ItemCode + "[n]= " + exp + "; break;}";
	} else {
		var end_old = 0;
		var sb = "";
		while (true) {
			var start_new = exp.indexOf("return", end_old);
			var end_new = exp.indexOf(";", start_new);
			if (start_new > 0 && end_new > start_new) {
				sb += exp.substring(end_old, start_new);
				var temp = exp.substring(start_new, end_new);
				temp = temp.replace('return', "");
				temp = "{ " + ItemCode + "[n]= " + temp + ";break;}";
				sb += temp;
				end_old = end_new + 1;
			} else {
				sb += exp.substring(end_old);
				break;
			}
		}
		return sb;
	}
}

/**
 * 计算收益和替换
 * */
function transProfitExpress(express, lsPolSchema) {
	//常用替换变量 可以增加
	var AppAge = lsPolSchema['insuredappage'];
	var Sex = lsPolSchema['insuredsex'];
	//主险数据
	var $PolM = null;
	var mainPolNo = lsPolSchema['mainpolno'];
	var LSPolDB = new dB('LSPol');
	LSPolDB['polno'] = mainPolNo;
	if (LSPolDB.getInfo()) {
		$PolM = LSPolDB;
		MainPolAmnt = $PolM['amnt'];
	}
	var InvestRiskDataDB = new dB('InvestRiskData');
	InvestRiskDataDB['signno'] = lsPolSchema['standbyflag3'];
	var InvestRiskDataSet = InvestRiskDataDB.query();
	var $SubPDH = new polSubDataHandler(InvestRiskDataSet, $PolM['years'], AppAge, lsPolSchema['standbyflag3']);

	return eval(express);
}

/**
 * 用LSPOL表中数据替换表达式
 * @param express 表达式
 * @param lsPolSchema POL表数据
 * */
function transExpress(express, lsPolSchema) {
	//修正大小写问题
	var expressArray = express.split('?');
	var tempExpress = '';
	for (var i = 0; i < expressArray.length; i++) {
		if (i % 2 != 0) {
			tempExpress += ('?' + expressArray[i].toLowerCase() + '?');
		} else {
			tempExpress += expressArray[i];
		}
	}
	// LSPOL表替换
	for (var obj in lsPolSchema) {
		eval("tempExpress = tempExpress.replace(/\\?" + obj + "\\?/g, lsPolSchema." + obj + ");");
	}

	//获取投保人信息
	var LSAppntDB = new dB('LSAppnt');
	LSAppntDB['contno'] = lsPolSchema['contno'];
	if (LSAppntDB.getInfo()) {
		var appntBirthday = LSAppntDB['appntbirthday'];
		var appntAge = pubFun.calInterval(appntBirthday, pubFun.getCurrentDate(), 'Y');
		tempExpress = tempExpress.replace(/\?appntsex\?/g, LSAppntDB['appntsex']);
		tempExpress = tempExpress.replace(/\?appntage\?/g, appntAge);
	}

	// 被保人信息的特殊替换
	tempExpress = tempExpress.replace(/\?appage\?/g, lsPolSchema['insuredappage']);
	tempExpress = tempExpress.replace(/\?sex\?/g, lsPolSchema['insuredsex']);

	return tempExpress;
}

/**
 * 获取全部数据
 * @mainPolNo 主险号
 * */
function calculateAll(mainPolNo) {

	var totalData = null;

	var LSPolDB = new dB('LSPol');
	LSPolDB['mainpolno'] = mainPolNo;
	var LSPolSet = LSPolDB.query();
	for (var m = 0; m < LSPolSet.length; m++) {
		var tempLSPolSchema = LSPolSet[m];
		var tempdata = calculate(tempLSPolSchema);
		if (totalData == null) {
			totalData = tempdata;
		} else {
			totalData = MergeCaculateData(totalData, tempdata);
		}
	}

	return totalData;
}

/**
 * 转换成HTML代码
 * @param data 数据
 * */
ProfitCaculator.prototype.toProfitTableHTML = function() {
	var data = calculateAll(this.mainPolNo);
	var cData = data.cData;
	var oriHData = data.hData;
	var reOrderTotalInfo = getTableHeadInfo(oriHData);

	reOrderInfoArr = HeadSubdivision(reOrderTotalInfo);
	var html = '';
	//组成表格
	for (var i = 0; i < reOrderInfoArr.length; i++) {
		reOrderInfo = reOrderInfoArr[i];
		var hData = reOrderInfo.reOrderHData;
		var years = cData[hData[0]].length;
		var groupHData = reOrderInfo.groupHData;

		html += ' <table width="100%" border="0" align="right" cellpadding="3" cellspacing="1" bgcolor="#BCDFFC" id="tableShow" class="scrollTable">';
		html += '<thead class="fixedHeader">';
		//收益表头部信息
		var firstHead = '<tr style="position:relative" bgcolor="#BCDFFC">';
		var secordHead = '<tr style="position:relative">'
		for (var m = 0; m < groupHData.length; m++) {
			var tempGroupHData = groupHData[m];
			if (tempGroupHData.childrenInfo.length == 1) {
				firstHead += ('<th height="25" style="position:relative" rowspan="2" align="center" valign="middle" bgcolor="#A2CBF9" class="hei"><strong>' + tempGroupHData.childrenInfo[0].Title + '</strong></th>');
			} else {
				firstHead += ('<th height="25" style="position:relative" colspan="' + tempGroupHData.childrenInfo.length + '" align="center" valign="middle" bgcolor="#A2CBF9" class="hei"><strong>' + tempGroupHData.Title + '</strong></th>');
				for (var n = 0; n < tempGroupHData.childrenInfo.length; n++) {
					secordHead += (' <th style="position:relative" align="center" valign="middle" bgcolor="#A2CBF9" class="hei"><strong>' + tempGroupHData.childrenInfo[n].Title + '</strong></th>');
				}
			}
		}
		firstHead += '</tr>'
		secordHead += '</tr>';
		html += (firstHead + secordHead + '</thead>');

		html += '<tbody>';

		for (var m = 0; m < years; m++) {
			if (m % 2 == 1) {
				html += '<tr align="right" valign="middle" bgcolor="#FFFFFF" class="code">';
			} else {
				html += '<tr align="right" valign="middle" bgcolor="#E9F3FE" class="black">';
			}
			for (var n = 0; n < hData.length; n++) {
				var tempData = cData[hData[n]][m];
				var fillNum = '';
				if (tempData == 0) {
					fillNum = '--'
				} else {
					fillNum = pubFun.formatNumberByThous(tempData);
				}
				html += ('<td align="center" valign="middle" class="hei" nowrap="" style="">' + fillNum + '</td>');
			}
			html += '</tr>';
		}

		html += '</tbody>';
		html += '</table>';
	}

	return html;
}
/**
 *读取表头
 * */
function getTableHeadInfo(hData) {
	var headerEleNameJSON = Ti.Filesystem.getFile(headerEleNamePath).read().toString();
	var headerEleNameObject = JSON.parse(headerEleNameJSON);

	var tempOrderFlagArr = [];
	var tempHeadInfos = {};
	for (var i = 0; i < hData.length; i++) {
		var tempStr = headerEleNameObject[hData[i]];
		var tempArr = tempStr.split('.');
		var flagInfo = tempArr[0];
		var flagInfoArr = flagInfo.split(':');
		var orderFlag = flagInfoArr[0];
		var parentId = flagInfoArr[1];
		var title = tempArr[1];
		var parentTitle = tempArr[2];
		var headInfo = {
			id : hData[i],
			title : title,
			parentId : parentId,
			parentTitle : parentTitle
		}
		tempOrderFlagArr.push(orderFlag);
		tempHeadInfos[orderFlag] = headInfo
	}

	var reOrderFlagArr = tempOrderFlagArr.sort();

	var reOrderData = [];
	var headInfoArr = [];
	for (var i = 0; i < reOrderFlagArr.length; i++) {
		headInfoArr.push(tempHeadInfos[reOrderFlagArr[i]]);
		reOrderData.push(tempHeadInfos[reOrderFlagArr[i]].id);
	};

	//分组排列
	var tempGroupId = '';
	var tempGroupInfo = {};
	var finalHeadInfoArr = [];
	for (var i = 0; i < headInfoArr.length; i++) {
		var tempHeadInfo = headInfoArr[i];
		if (tempHeadInfo.parentId != tempGroupId) {
			tempGroupInfo = {
				Id : tempHeadInfo.parentId,
				Title : tempHeadInfo.parentTitle,
				childrenInfo : []
			}
			tempGroupInfo.childrenInfo.push({
				Id : tempHeadInfo.id,
				Title : tempHeadInfo.title
			});
			finalHeadInfoArr.push(tempGroupInfo);
			tempGroupId = tempHeadInfo.parentId;
		} else {
			tempGroupInfo.childrenInfo.push({
				Id : tempHeadInfo.id,
				Title : tempHeadInfo.title
			});
		}
	}

	var reslut = {
		reOrderHData : reOrderData,
		groupHData : finalHeadInfoArr
	}
	return reslut;
}

/**
 * 收益文档HTML
 * */
ProfitCaculator.prototype.toProfitDocHTML = function() {
	var caldatariskresourceJSON = Ti.Filesystem.getFile(caldatariskresourcePath).read().toString();
	var caldatariskresourceObject = JSON.parse(caldatariskresourceJSON);
	var mainRiskDocFlag = caldatariskresourceObject[this.mainRiskCode + 'DOC'].toString();
	var headintroduceJSON = Ti.Filesystem.getFile(headintroducePath).read().toString();
	var headintroduceObject = JSON.parse(headintroduceJSON);

	var htmlCode = '<table>'

	htmlCode += createProfitDoc(this.mainRiskCode, this.mainPolNo, headintroduceObject, mainRiskDocFlag);

	for (var i = 0; i < this.subRisks.length; i++) {
		var tempRiskCode = this.subRisks[i];
		var tempRiskDocFlag = caldatariskresourceObject[tempRiskCode + 'DOC'].toString();
		htmlCode += createProfitDoc(tempRiskCode, this.mainPolNo, headintroduceObject, tempRiskDocFlag);
	};
	htmlCode += '</table>'
	return htmlCode;
}
/**
 * 计算单个险种的收益文档
 * */
function createProfitDoc(riskCode, mainPolNo, headintroduceObject, mainRiskDocFlag) {
	var LMRiskAppDB = new dB('LMRiskApp');
	LMRiskAppDB['riskcode'] = riskCode;
	var riskName = ''
	if (LMRiskAppDB.getInfo()) {
		riskName = LMRiskAppDB['riskname'];
	}
	//获取收益数据
	var LSPolDB = new dB('LSPol');
	LSPolDB['mainpolno'] = mainPolNo;
	LSPolDB['riskcode'] = riskCode;
	var LSPolSet = LSPolDB.query();
	var cData = calculate(LSPolSet[0]).cData;

	//组合html代码
	var html = '';

	var flagArr = mainRiskDocFlag.split(',');
	for (var i = 0; i < flagArr.length; i++) {
		var tempColor = '#FFFFFF';
		if (i % 2 == 0) {
			tempColor = '#F7FCFF';
		}
		html += '<tr align="center" valign="middle">';
		var tempStr = headintroduceObject[flagArr[i]];
		var tempArr = tempStr.split('：');
		var afterReplace = tempArr[1];
		for (var obj in cData) {
			var minValue = pubFun.formatNumberByThous(cData[obj][0]);
			var maxValue = pubFun.formatNumberByThous(cData[obj][cData[obj].length - 1]);
			eval("afterReplace = afterReplace.replace(/\#" + obj + "\#/g, maxValue)");
			eval("afterReplace = afterReplace.replace(/\\?" + obj + "\\?/g, minValue)");
		}
		html += ('<td width="30%" height="50" bgcolor="#F1F8FE" class="bold_title">' + tempArr[0] + '</td>');
		html += ('<td width="70%" height="50" align="left" valign="middle" bgcolor="' + tempColor + '" class="style2">' + (afterReplace == '无' ? '' : afterReplace) + '</td>');
		html += ' </tr>';
	}
	return html;
}

/**
 * 转换为生成受益图的数据
 * */
ProfitCaculator.prototype.toProfitChart = function() {
	//保险数据信息
	var insuredName = '被保人姓名';
	var LSPolDB = new dB('LSPol');
	LSPolDB['polno'] = this.mainPolNo;
	if (LSPolDB.getInfo()) {
		insuredName = LSPolDB['insuredname'];
	}

	//险种信息
	var riskName = '险种名称'
	var LMRiskAppDB = new dB('LMRiskApp');
	LMRiskAppDB['riskcode'] = this.mainRiskCode;
	if (LMRiskAppDB.getInfo()) {
		var riskName = LMRiskAppDB['riskname'];
	}

	//收益数据
	var data = calculateAll(this.mainPolNo);
	var cData = data.cData;
	var hData = data.hData;

	//读取picElement文件
	var tempPicData = [];

	var picElementJSON = Ti.Filesystem.getFile(picElementPath).read().toString();
	var picElementObject = JSON.parse(picElementJSON);
	//区域图
	var areaStr = picElementObject['area'];
	var areaArr = areaStr.split(',');
	for (var i = 0; i < areaArr.length; i++) {
		var temparea = areaArr[i];
		var tempareaArr = temparea.split(':');
		var value = tempareaArr[0];
		if (hData.indexOf(value) != -1) {
			var tempData = {
				type : 'area',
				value : tempareaArr[0],
				title : tempareaArr[1]
			}
			Ti.API.warn('[ProfitCaculator]面积图增加数据：' + value);
			tempPicData.push(tempData);
		}
	};
	//线图
	var splineStr = picElementObject['line'];
	var splineArr = splineStr.split(',');
	for (var i = 0; i < splineArr.length; i++) {
		var tempspline = splineArr[i];
		var tempsplineArr = tempspline.split(':');
		var value = tempsplineArr[0];
		if (hData.indexOf(value) != -1) {
			var tempData = {
				type : 'spline',
				value : tempsplineArr[0],
				title : tempsplineArr[1]
			}
			Ti.API.warn('[ProfitCaculator]线图增加数据：' + value);
			tempPicData.push(tempData);
		}
	};
	//柱状图
	var barStr = picElementObject['bar'];
	var barArr = barStr.split(',');
	for (var i = 0; i < barArr.length; i++) {
		var tempbar = barArr[i];
		var tempbarArr = tempbar.split(':');
		var value = tempbarArr[0];
		if (hData.indexOf(value) != -1) {
			var tempData = {
				type : 'bar',
				value : tempbarArr[0],
				title : tempbarArr[1]
			}
			Ti.API.warn('[ProfitCaculator]柱状图增加数据：' + value);
			tempPicData.push(tempData);
		}
	};

	var fireData = insuredName + ',' + riskName + ';'
	//横坐标增加
	fireData += cData['BDND'].toString();
	for (var i = 0; i < tempPicData.length; i++) {
		fireData += (';' + tempPicData[i].type + ',' + tempPicData[i].title + ',' + cData[tempPicData[i].value].toString());
	}
	return fireData;
}
/**
 * 分割头部列
 * */
function HeadSubdivision(oriReslutData) {
	var reslut = [];
	//默认全部存在列
	var DEFAULT_ALLIN_INDEX = [0, 1, 2];
	//默认宽度数量(除去全部存在的列外)
	var DEFAULT_WIDTH_COUNT = 8;
	//默认头部列
	var reOrderHData = oriReslutData.reOrderHData;
	var groupHData = oriReslutData.groupHData;

	var tempReOrderHData = [];
	var tempGroupHData = [];

	var tempCount = 0;

	for (var i = 3; i < groupHData.length; i++) {
		//先填充默认值
		if (tempReOrderHData.length == 0 && tempGroupHData.length == 0) {
			for (var m = 0; m < DEFAULT_ALLIN_INDEX.length; m++) {
				tempReOrderHData.push(reOrderHData[m]);
				tempGroupHData.push(groupHData[m]);
			}
		}

		var tempLength = groupHData[i].childrenInfo.length;
		if (tempCount + tempLength > DEFAULT_WIDTH_COUNT) {
			reslut.push({
				reOrderHData : tempReOrderHData,
				groupHData : tempGroupHData
			})
			tempReOrderHData = [];
			tempGroupHData = [];
			tempCount = 0;
			i--;
		} else {
			tempGroupHData.push(groupHData[i]);
			for (var n = 0; n < tempLength; n++) {
				tempReOrderHData.push(groupHData[i].childrenInfo[n].Id);
			}
			tempCount += tempLength;
		}

		if (i == groupHData.length - 1) {
			reslut.push({
				reOrderHData : tempReOrderHData,
				groupHData : tempGroupHData
			});
		}
	}
	return reslut;
}

module.exports = ProfitCaculator;
